dofile("objs.lua")
dofile("collision.lua")

function movC(c,x,y)
   c.center.x=c.center.x+x
   c.center.y=c.center.y+y
end

function movR(r,x,y)
   r.minx=r.minx+x
   r.miny=r.miny+y
   r.maxx=r.maxx+x
   r.maxy=r.maxy+y
end

function copyO(obj)
  local o = nil
  if obj.type==T_CIRCLE then
    o = newCircle(obj.d.center.x+obj.x,obj.d.center.y+obj.y,obj.d.r)
    o.tcol = tcolC
    o.mov = movC
  end
  if obj.type==T_RECT then
    o = newRect(obj.d.minx+obj.x,obj.d.miny+obj.y,obj.d.maxx+obj.x,obj.d.maxy+obj.y)
    o.tcol = tcolR
    o.mov = movR
  end

  return o
end

function mov(omov,ostats,t,onCollision)
   local szpeq = 0.001

   local d={}
   d.x=0
   d.y=0

   local o = copyO(omov)

   local vel = {}
   vel.x = omov.vel.x
   vel.y = omov.vel.y

   local sz = 0
   local ignore = {}

   vel.sz = math.sqrt(vel.x*vel.x+vel.y*vel.y)
   sz = vel.sz * t
   while sz>szpeq do
      vel.nx = vel.x/vel.sz
      vel.ny = vel.y/vel.sz

      local tcol,ocolIdx,ncx,ncy=o.tcol(o,ostats,vel,t,ignore)
      if tcol==0 then
         ignore[ocolIdx]=1
      elseif (tcol>t) or (tcol<0) then
         d.x=d.x+vel.x*t
         d.y=d.y+vel.y*t
         sz=0
      elseif tcol>0 then
         local c,s=onCollision(omov,ostats[ocolIdx],ncx,ncy)

         if c==1 then
            local dessz = vel.sz*tcol

            if dessz>szpeq then
               local desx = vel.x*tcol
               local desy = vel.y*tcol
               desx = desx - vel.nx*szpeq
               desy = desy - vel.ny*szpeq
               o.mov(o,desx,desy)
               d.x = d.x + desx
               d.y = d.y + desy
            end
            t=t-tcol
            if (t<=0) or (s~=1) then
               sz = 0
            else
               local dot = vel.nx*ncx+vel.ny*ncy
               local projx = ncx*dot
               local projy = ncy*dot
               vel.x = (vel.nx-projx)*vel.sz
               vel.y = (vel.ny-projy)*vel.sz

               vel.sz = math.sqrt(vel.x*vel.x+vel.y*vel.y)
               sz = vel.sz * t
            end
         else
            ignore[ocolIdx]=1
         end
      end
   end

   return d
end

